

#import "PUHomeCell.h"

@implementation PUHomeCell


-(id)initWithFrame:(CGRect)frame
{
    if (self=[super initWithFrame:frame])
    {
        
        self.layer.cornerRadius = 8;
        self.contentView.layer.cornerRadius = 8.0f;
        self.contentView.layer.masksToBounds = YES;
        self.backgroundColor=[UIColor whiteColor];

        self.showImage=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.width*1.176)];
//        self.showImage.image=[UIImage imageNamed:@"moment_pic_1"];
        self.showImage.contentMode=UIViewContentModeScaleAspectFill;
        self.showImage.clipsToBounds = YES;
//        self.showImage.layer.cornerRadius = 5;
        self.showImage.backgroundColor=[UIColor colorWithHex:0xDCDCDC];
        self.showImage.layer.masksToBounds=YES;
        [self addSubview:self.showImage];
        
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.showImage.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(8, 8)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = self.showImage.bounds;
        maskLayer.path = maskPath.CGPath;
        self.showImage.layer.mask = maskLayer;
        
        self.headImage=[[UIImageView alloc]init];
        self.headImage.contentMode=UIViewContentModeScaleAspectFill;
        self.headImage.layer.borderColor = [UIColor whiteColor].CGColor;
        self.headImage.layer.borderWidth = 1.0;
        self.headImage.layer.masksToBounds=YES;
        self.headImage.backgroundColor=[UIColor colorWithHex:0xDCDCDC];
        [self addSubview:self.headImage];
        
        self.nameLab = [[UILabel alloc] init];
        self.nameLab.font=[UIFont boldSystemFontOfSize:15];
        self.nameLab.textColor = [UIColor whiteColor];
        [self addSubview:self.nameLab];
        
        
        NSString *str=@"昵称";
        // 左边视图
       self.titleLab = [[UILabel alloc] init];
       self.titleLab.text=str;
       self.titleLab.font=[UIFont boldSystemFontOfSize:15];
       self.titleLab.textColor = [UIColor blackColor];
//       self.titleLab.backgroundColor = [UIColor redColor];
       [self addSubview:self.titleLab];
        
        
        
        CGSize size = [str sizeWithAttributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:14]}];
        CGFloat width = ceil(size.width);
        self.titleLab.frame=CGRectMake(8*KWidthScale, self.showImage.originY+self.showImage.size.height+8*KWidthScale,width, 20*KWidthScale);
        
       NSString *str2=@"";
       self.detailsLab = [[UILabel alloc] init];
       self.detailsLab.text=str2;
       self.detailsLab.font=[UIFont systemFontOfSize:10];
       self.detailsLab.textColor = [UIColor colorWithHex:0x888888];
//       self.detailsLab.backgroundColor = [UIColor greenColor];
       [self addSubview:self.detailsLab];
        
        CGSize size2 = [str2 sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:10]}];
        CGFloat width2 = ceil(size2.width);
        self.detailsLab.frame=CGRectMake(8*KWidthScale, self.titleLab.originY+self.titleLab.size.height+4*KWidthScale,width2, 14*KWidthScale);
        
//        NSString *str3=@"我们每个人都有去过很多很多的地方，但是有哪些是…";
//       self.signatureLab = [[UILabel alloc] init];
//       self.signatureLab.text=str3;
//       self.signatureLab.font=[UIFont systemFontOfSize:11];
//       self.signatureLab.textColor = [UIColor colorWithHex:0x888888];
//        self.signatureLab.textAlignment=NSTextAlignmentRight;
//       self.signatureLab.backgroundColor = [UIColor purpleColor];
//       [self addSubview:self.signatureLab];
        
       
        
        self.JBImage=[[UIImageView alloc]init];
        self.JBImage.image=[UIImage imageNamed:@"淘花金币"];
        [self addSubview:self.JBImage];
        
        self.collectBtn = [[UIButton alloc]init];
        [self.collectBtn setImage:[UIImage imageNamed:@"收藏_未选中3"] forState:UIControlStateNormal];
        [self.collectBtn setImage:[UIImage imageNamed:@"收藏_选中3"] forState:UIControlStateSelected];
        [self.collectBtn addTarget:self action:@selector(collectAction) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:self.collectBtn];
        [self.collectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.offset = -8;
            make.bottom.offset = -16;
            make.width.height.offset = 35;
        }];
    }
     return self;
}

- (void)collectAction {
    
    if ([Config getToken]==nil) {
        if ([self.delegate respondsToSelector:@selector(noLogin)]) {
            [self.delegate noLogin];
        }
        return;
    }
    
    [self collectdata];
    
    
    self.taohuaModel.isCollect = !self.taohuaModel.isCollect;
    self.collectBtn.selected = self.taohuaModel.isCollect;
    if (self.collectBtn.selected) {
        self.taohuaModel.count ++;
    }
    else {
        self.taohuaModel.count --;
    }
    
    if (self.collectBlock) {
        self.collectBlock();
    }
}

-(void)collectdata{
    //创建一个归档文件夹
    NSArray *library = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *strLib = [[library objectAtIndex:0] stringByAppendingPathComponent:@"archive"];
    BOOL directory = YES;
    if (![[NSFileManager defaultManager] fileExistsAtPath:strLib isDirectory:&directory])
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:strLib withIntermediateDirectories:NO attributes:nil error:nil];
    }
    //归档
    NSString *entityArchive = [strLib stringByAppendingPathComponent:[NSString stringWithFormat:@"collectDataArchive%@",[Config getID]]];
//    [NSKeyedArchiver archiveRootObject:data toFile:entityArchive];
    //数据源从归档中读出
    NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:entityArchive];
    NSLog(@"%@",array);
    if(array.count==0){
        array=[NSMutableArray array];
    }
    if (self.taohuaModel.isCollect==NO) {
        
        NSDictionary * d1 = @{
            @"name":self.taohuaModel.name,
        };
        [array insertObject:d1 atIndex:0];
        [NSKeyedArchiver archiveRootObject:array toFile:entityArchive];
        NSMutableArray *array2 = [NSKeyedUnarchiver unarchiveObjectWithFile:entityArchive];
        NSLog(@"%@",array2);
    }else{
        for (int i=0; i<array.count; i++) {
            NSDictionary *dic=array[i];
            if ([dic[@"name"] isEqualToString:self.taohuaModel.name]) {
                [array removeObjectAtIndex:i];
            }
        }
        [NSKeyedArchiver archiveRootObject:array toFile:entityArchive];
        NSMutableArray *array2 = [NSKeyedUnarchiver unarchiveObjectWithFile:entityArchive];
        NSLog(@"%@",array2);
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"foodCollcetNotification" object:self userInfo:nil];
}

// 自定义Layout
-(void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes
{
    //cell背景阴影
    self.layer.shadowColor = [UIColor lightGrayColor].CGColor;
    self.layer.shadowOffset =  CGSizeMake(0,0);
    self.layer.shadowRadius =3.0f;
    self.layer.shadowOpacity =0.5f;
    self.layer.masksToBounds =NO;
    self.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:self.contentView.layer.cornerRadius].CGPath;

//    [CATransaction begin];
//    [CATransaction setDisableActions:YES];
}
-(void)daShanAction{
    if ([self.delegate respondsToSelector:@selector(clickBtn:)]) {
        [self.delegate clickBtn:self];
    }
}


-(void)setModel:(PUCityListModel *)model{
    _model=model;
    
    self.titleLab.text=model.nickname;
    CGSize size = [model.nickname sizeWithAttributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:15]}];
    CGFloat width = ceil(size.width);
    self.titleLab.frame=CGRectMake(8*KWidthScale, self.showImage.originY+self.showImage.size.height+8*KWidthScale,width, 20*KWidthScale);
    
    self.headImage.frame=CGRectMake(8*KWidthScale, 8*KWidthScale,32*KWidthScale, 32*KWidthScale);
    self.headImage.layer.cornerRadius = self.headImage.frame.size.height/2;
    
    
    self.nameLab.text=model.nickname;
    
    CGSize nameLabsize = [model.nickname sizeWithAttributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:15]}];
    CGFloat nameLabwidth = ceil(nameLabsize.width);
//    self.titleLab.frame=CGRectMake(8*KWidthScale, self.showImage.originY+self.showImage.size.height+8*KWidthScale,nameLabwidth, 18*KWidthScale);
    
    self.nameLab.frame=CGRectMake(6*KWidthScale+self.headImage.frame.origin.x+self.headImage.frame.size.width, 14*KWidthScale,nameLabwidth, 18*KWidthScale);
    
    NSString *avatar=model.avatar;
    NSDictionary *saveOpen_app_config = [Config getOpenAppConfig];
    if (saveOpen_app_config!=nil) {
        NSString *cos_url=saveOpen_app_config[@"cos_url"];
        NSString *cos_auth=saveOpen_app_config[@"cos_auth"];
        if (avatar.length>cos_url.length) {
            NSString *urlSuffix = [avatar substringFromIndex:cos_url.length];
            
            NSString *timeStamp=[AES128 getNowTimeStamp];
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            NSString *str=[NSString stringWithFormat:@"homeHeadImage%d",model.ID];
            NSString *t=[userDefaults objectForKey:str];
            if (t!=nil&&![t isEqualToString:@""]) {
                timeStamp=t;
            }else{
                [userDefaults setObject:timeStamp forKey:str];
                [userDefaults synchronize];
            }
            NSString *urlStr=[NSString stringWithFormat:@"%@%@%@",cos_auth,urlSuffix,timeStamp];
            NSData *data = [urlStr dataUsingEncoding:NSUTF8StringEncoding];
            
            if (data) {
                NSData *md5Result = [AES128 dataWithMD5Hash:data];
                NSString *hexString = [AES128 hexStringFromData:md5Result];
                
                avatar=[NSString stringWithFormat:@"%@?sign=%@&t=%@",avatar,hexString,timeStamp];
                [self.showImage sd_setImageWithURL:[NSURL URLWithString:avatar] placeholderImage:[UIImage imageNamed:@""]];
                [self.headImage sd_setImageWithURL:[NSURL URLWithString:avatar] placeholderImage:[UIImage imageNamed:@""]];
                
            } else {
                // 转换失败
                NSLog(@"Failed to convert string to NSData.");
            }
        }
    }
    
    NSString *str=@"123";
    
    NSString *app_icp=str;
    NSString *topStr=app_icp;
    NSString *s=[NSString stringWithFormat:@"%@",topStr];
   
    CGSize size2 = [s sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:20]}];
    CGFloat width2 = ceil(size2.width);
    self.detailsLab.frame=CGRectMake(8*KWidthScale, self.titleLab.originY+self.titleLab.size.height+4*KWidthScale,width2, 28*KWidthScale);
    
//    NSMutableAttributedString *hogan1 = [[NSMutableAttributedString alloc] initWithString:s];
//    [hogan1 addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:20] range:NSMakeRange(0, s.length)];
//    [hogan1 addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHex:0xFF729A] range:NSMakeRange(0, s.length)];
////    [hogan1 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:10] range:NSMakeRange(0, 1)];
////    [hogan1 addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHex:0xFF729A] range:NSMakeRange(0,1)];
//    self.detailsLab.attributedText = hogan1;
    
    self.JBImage.frame=CGRectMake(self.detailsLab.originX+self.detailsLab.size.width+5*KWidthScale, self.titleLab.originY+self.titleLab.size.height+8*KWidthScale,20*KWidthScale, 20*KWidthScale);
    
    self.signatureLab.frame=CGRectMake(8*KWidthScale, self.titleLab.originY+self.titleLab.size.height+9*KWidthScale,self.frame.size.width-8*KWidthScale*2, 18*KWidthScale);

    
    NSString *str3=@"";
    if (model.intro!=nil&&![model.intro isEqualToString:@""]) {
        str3=model.intro;
    }else{
        str3=@"这个家伙很懒，什么都没有留下";
    }
    self.signatureLab.text=@"已售3000+";
    
}
-(void)setTaohuaModel:(PUFoodModel *)taohuaModel{
    
    
//    NSDictionary * d1 = @{@"flowers_name":@"白玉兰",
//                          @"flowers_image":[NSArray arrayWithObjects:@"taohua1", nil],
//                          @"flowers_describe":@"漂亮的白玉兰花",
//                          @"flowers_JG":@"50",
//                          @"flowers_XL":@"10",
//                          @"flowers_KC":@"10",
//                          @"username":@"靓仔",
//                          @"userimage":@"0",
//                         };
    _taohuaModel = taohuaModel;
    
    self.titleLab.text=taohuaModel.name;
    CGSize size = [taohuaModel.name sizeWithAttributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:15]}];
    CGFloat width = ceil(size.width);
    self.titleLab.frame=CGRectMake(8*KWidthScale, self.showImage.originY+self.showImage.size.height+8*KWidthScale,width, 20*KWidthScale);
    
    self.headImage.frame=CGRectMake(8*KWidthScale, 8*KWidthScale,32*KWidthScale, 32*KWidthScale);
    self.headImage.layer.cornerRadius = self.headImage.frame.size.height/2;
    
    
    self.nameLab.text=taohuaModel.username;
    
    CGSize nameLabsize = [taohuaModel.username sizeWithAttributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:15]}];
    CGFloat nameLabwidth = ceil(nameLabsize.width);
//    self.titleLab.frame=CGRectMake(8*KWidthScale, self.showImage.originY+self.showImage.size.height+8*KWidthScale,nameLabwidth, 18*KWidthScale);
    
    self.nameLab.frame=CGRectMake(6*KWidthScale+self.headImage.frame.origin.x+self.headImage.frame.size.width, 14*KWidthScale,nameLabwidth, 18*KWidthScale);
//    self.showImage.image=[UIImage imageNamed:taohuaModel.flowers_image[0]];
    [self.showImage sd_setImageWithURL:[NSURL URLWithString:taohuaModel.cover]];
    
    self.collectBtn.selected = taohuaModel.isCollect;
    
    NSString *s=[NSString stringWithFormat:@"%ld人已收藏",taohuaModel.count];
    self.detailsLab.text=s;
    CGSize size2 = [s sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:20]}];
    CGFloat width2 = ceil(size2.width);
    self.detailsLab.frame=CGRectMake(8*KWidthScale, self.titleLab.originY+self.titleLab.size.height*KWidthScale,width2, 28*KWidthScale);
    
//    NSMutableAttributedString *hogan1 = [[NSMutableAttributedString alloc] initWithString:s];
//    [hogan1 addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:20] range:NSMakeRange(0, s.length)];
//    [hogan1 addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHex:0xFF729A] range:NSMakeRange(0, s.length)];
////    [hogan1 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:10] range:NSMakeRange(0, 1)];
////    [hogan1 addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHex:0xFF729A] range:NSMakeRange(0,1)];
//    self.detailsLab.attributedText = hogan1;
    
    self.JBImage.frame=CGRectMake(self.detailsLab.originX+self.detailsLab.size.width+5*KWidthScale, self.titleLab.originY+self.titleLab.size.height+8*KWidthScale,20*KWidthScale, 20*KWidthScale);
    
//    self.signatureLab.frame=CGRectMake(8*KWidthScale, self.titleLab.originY+self.titleLab.size.height+9*KWidthScale,self.frame.size.width-8*KWidthScale*2, 18*KWidthScale);
//
//    self.signatureLab.text=[NSString stringWithFormat:@"已售%@+",taohuaModel.flowers_XL];
    
    NSString *avatar=taohuaModel.userimage;
    NSDictionary *saveOpen_app_config = [Config getOpenAppConfig];
    NSString *cos_url=@"";
    NSString *cos_auth=@"";
    NSString *urlSuffix=@"";
    if (saveOpen_app_config!=nil) {
        cos_url=saveOpen_app_config[@"cos_url"];
        NSLog(@"%@",cos_url);//https://cos.nnyc123.cn
        
        cos_auth=saveOpen_app_config[@"cos_auth"];
        if (avatar.length>cos_url.length) {
            NSLog(@"%@",cos_auth);//ssM7AOlb5Xio2015kLKmayc
            urlSuffix = [avatar substringFromIndex:cos_url.length];
            NSLog(@"%@",urlSuffix);//common/app/male.png
       
            NSString *timeStamp=[AES128 getNowTimeStamp];//1744628907
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            NSString *str=[NSString stringWithFormat:@"MineHeadtimeStamp%@",[Config getID]];
            NSString *t=[userDefaults objectForKey:str];
            if (t!=nil&&![t isEqualToString:@""]) {
                timeStamp=t;
            }else{
                [userDefaults setObject:timeStamp forKey:str];
                [userDefaults synchronize];
            }
            NSString *urlStr=[NSString stringWithFormat:@"%@%@%@",cos_auth,urlSuffix,timeStamp];
            NSLog(@"%@",urlStr);//ssM7AOlb5Xio2015kLKmayc/common/app/male.png1744628907
            NSData *data = [urlStr dataUsingEncoding:NSUTF8StringEncoding];
            
            if (data) {
                // 转换成功，data 包含了UTF-8编码的字节数组
                // 例如，你可以将NSData写入文件或通过网络发送
                NSLog(@"转换成功");
                
                NSData *md5Result = [AES128 dataWithMD5Hash:data];
                NSString *hexString = [AES128 hexStringFromData:md5Result];
                
                NSString *url=[NSString stringWithFormat:@"%@?sign=%@&t=%@",avatar,hexString,timeStamp];
                [self.headImage sd_setImageWithURL:[NSURL URLWithString:url]];
            } else {
                // 转换失败
                NSLog(@"Failed to convert string to NSData.");
            }
        }
    }
}

@end
